<template>
  <el-dialog
    model-value="dialogVisible"
    :title="dialogTitle"
    width="95%"
    @close="handleClose"
  >
    <el-row>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <div class="button-cls">
                <div class="title">已选考题：</div>
                <el-button
                  link
                  type="danger"
                  :icon="Delete"
                  v-hasPerm="['examManage:paperManage:remove']"
                  :disabled="selectMultiple"
                  @click="selectMultipleHandler"
                  >删除考题</el-button
                >
              </div>
            </div>
          </template>
          <el-table
            :data="questionSelectList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="题目名字"
              align="center"
              prop="questionName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="题目分数"
              align="center"
              prop="questionScore"
            />
            <el-table-column
              label="问题类型"
              align="center"
              prop="questionTypeLabel"
            />
            <el-table-column
              label="难易度"
              align="center"
              prop="questionLevelLabel"
            >
            </el-table-column>
          </el-table>
          <pagination
            v-show="questionSelectTotal > 0"
            :total="questionSelectTotal"
            v-model:page="querySelectParams.pageNum"
            v-model:limit="querySelectParams.pageSize"
            @pagination="questionSelectHandler"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <div class="button-cls">
                <div class="title">考题库：</div>
                <el-button
                  link
                  type="primary"
                  :icon="EditPen"
                  v-hasPerm="['examManage:paperManage:edit']"
                  :disabled="selectExMultiple"
                  @click="selectExMultipleHandler"
                  >选择考题</el-button
                >
              </div>
            </div>
          </template>
          <el-form
            :model="queryNoSelectParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="90px"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="问题难易度" prop="questionLevelId">
                  <el-select
                    v-model="queryNoSelectParams.questionLevelId"
                    placeholder="问题难易度"
                    @change="handleQuery"
                  >
                    <el-option
                      v-for="item in questionLevelList"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select> </el-form-item
              ></el-col>

              <el-col :span="12">
                <el-form-item label="问题分类" prop="questionType">
                  <el-select
                    v-model="queryNoSelectParams.questionType"
                    placeholder="问题分类"
                    @change="handleQuery"
                  >
                    <el-option
                      v-for="item in questionTypeList"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select> </el-form-item
              ></el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="题目名字" prop="questionName">
                  <el-input
                    v-model="queryNoSelectParams.questionName"
                    placeholder="请输入题目名字"
                    maxlength="120"
                    show-word-limit
                    clearable
                    @keyup.enter="handleQuery"
                  /> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="handleQuery"
                    >搜索</el-button
                  >
                  <el-button :icon="Refresh" @click="resetQuery"
                    >重置</el-button
                  >
                </el-form-item></el-col
              >
            </el-row>
          </el-form>
          <el-table
            :data="questionNoSelectList"
            @selection-change="handleExSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              v-model="selectedRows"
            />
            <el-table-column
              label="题目名字"
              align="center"
              prop="questionName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="题目分数"
              align="center"
              prop="questionScore"
            />
            <el-table-column
              label="问题类型"
              align="center"
              prop="questionTypeLabel"
            />
            <el-table-column
              label="难易度"
              align="center"
              prop="questionLevelLabel"
            />
          </el-table>
          <pagination
            v-show="questionNoSelectTotal > 0"
            :total="questionNoSelectTotal"
            v-model:page="queryNoSelectParams.pageNum"
            v-model:limit="queryNoSelectParams.pageSize"
            @pagination="questionNoSelectHandler"
          />
        </el-card>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
export default {
  name: "paperAddQuestion",
};
</script>
<script setup>
import {
  ref,
  defineProps,
  defineEmits,
  onMounted,
  watch,
  nextTick,
  toRefs,
  getCurrentInstance,
} from "vue";
import { ElMessage } from "element-plus";
import {
  addQuestionIntoPaper,
  batchRemovePaperQuestion,
} from "@/api/examManage/paperManage";
import { listDictData } from "@/api/sys/dictData";

import { listByPaperId, listByExPaperId } from "@/api/examManage/question";
import {
  Search,
  Plus,
  Refresh,
  Edit,
  Delete,
  EditPen,
} from "@element-plus/icons-vue";
const selectMultiple = ref(true);
const selectExMultiple = ref(true);
const questionList = ref([]);
const exQuestionList = ref([]);
const showSearch = ref(true);
const props = defineProps({
  paperId: {
    type: Number,
    default: -1,
    required: true,
  },
  paperTotal: {
    type: Number,
    default: -1,
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});
const emits = defineEmits(["update:modelValue","initList"]);
const questionSelectList = ref([]);
const questionNoSelectList = ref([]);
const questionSelectTotal = ref(0);
const questionNoSelectTotal = ref(0);
const selectedRows = ref([]);
const paperInfo = ref({
  paperId: "",
  paperAnswer: "",
});
const querySelectParams = ref({
  pageNum: 1,
  pageSize: 10,
  questionName: null,
  questionType: null,
  createTime: null,
  paperId: null,
  params: {},
});
const queryNoSelectParams = ref({
  pageNum: 1,
  pageSize: 10,
  questionName: null,
  questionType: null,
  createTime: null,
  paperId: null,
  questionLevelId: null,
  params: {},
});
const questionLevelList = ref([]);
const questionTypeList = ref([]);
const { proxy } = getCurrentInstance();

/** 搜索按钮操作 */
function handleQuery() {
  queryNoSelectParams.value.pageNum = 1;
  questionNoSelectHandler();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 已选考题多选框选中数据
function handleSelectionChange(selection) {
  questionList.value = selection;
  selectMultiple.value = !selection.length;
}
const selectMultipleHandler = () => {
  let paperJoinQuestionList = [];
  questionList.value.map((t) => {
    paperJoinQuestionList.push({
      paperId: props.paperId,
      questionId: t.questionId,
    });
  });
  // selectMultiple.value = true;
  batchRemovePaperQuestion(paperJoinQuestionList).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      questionSelectHandler();
      questionNoSelectHandler();
    }
  });
};
// 考题库多选框选中数据
function handleExSelectionChange(selection) {
  exQuestionList.value = selection;
  selectExMultiple.value = !selection.length;
}
const selectExMultipleHandler = () => {
  let paperJoinQuestionList = [];
  let count = questionSelectList.value.reduce((pre, current) => {
    return pre + current.questionScore;
  }, 0);
  let countRest = exQuestionList.value.reduce((pre, current) => {
    return pre + current.questionScore;
  }, 0);
  if (Number(count) + Number(countRest) > Number(props.paperTotal)) {
    ElMessage.error(`分数超过了试卷${props.paperTotal}总分`);
    return;
  }
  let paperId = props.paperId;
  let answerList = [];
  exQuestionList.value.map((t) => {
    answerList.push(t.questionId + "-" + t.answer.replace(/,/g,'') + "-" + t.questionScore);
    paperJoinQuestionList.push({
      paperId: props.paperId,
      questionId: t.questionId,
    });
  });
  let paperAnswer = answerList.join("x");

  addQuestionIntoPaper({ paperId, paperAnswer, paperJoinQuestionList }).then(
    (res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        questionSelectHandler();
        questionNoSelectHandler();
      }
    }
  );
};
const handleClose = () => {
  emits("update:modelValue", false);
  emits("initList")
};
const initData = async () => {
  listDictData({
    pageNum: 1,
    pageSize: 20,
    dictType: "question_level",
  }).then((res) => {
    questionLevelList.value = res.data.rows;
  });
  listDictData({
    pageNum: 1,
    pageSize: 20,
    dictType: "question_type",
  }).then((res) => {
    questionTypeList.value = res.data.rows;
  });
};
const handleConfirm = async () => {};
const questionSelectHandler = async () => {
  querySelectParams.value.params.paperId = props.paperId;
  const questionSelectRes = await listByPaperId(querySelectParams.value);
  questionSelectRes.data.rows.map((t) => {
    t.questionLevelLabel = "";
    t.questionTypeLabel = "";
    let obj = questionLevelList.value.find(
      (m) => m.dictValue == t.questionLevelId
    );
    if (obj) {
      t.questionLevelLabel = obj.dictLabel;
    }
    let _obj = questionTypeList.value.find(
      (m) => m.dictValue == t.questionType
    );
    if (_obj) {
      t.questionTypeLabel = _obj.dictLabel;
    }
    return t;
  });
  questionSelectList.value = questionSelectRes.data.rows;
  questionSelectTotal.value = questionSelectRes.data.total;
};
const questionNoSelectHandler = async () => {
  queryNoSelectParams.value.params.paperId = props.paperId;
  const questionNoSelectRes = await listByExPaperId(queryNoSelectParams.value);
  questionNoSelectRes.data.rows.map((t) => {
    t.questionLevelLabel = "";
    t.questionTypeLabel = "";
    let obj = questionLevelList.value.find(
      (m) => m.dictValue == t.questionLevelId
    );
    if (obj) {
      t.questionLevelLabel = obj.dictLabel;
    }
    let _obj = questionTypeList.value.find(
      (m) => m.dictValue == t.questionType
    );
    if (_obj) {
      t.questionTypeLabel = _obj.dictLabel;
    }
    return t;
  });
  questionNoSelectList.value = questionNoSelectRes.data.rows;
  questionNoSelectTotal.value = questionNoSelectRes.data.total;
};
watch(
  () => props.dialogVisible,
  async (newValue) => {
    if (newValue) {
      questionSelectHandler();
      questionNoSelectHandler();
    }
  }
);

onMounted(() => {
  initData();
});
</script>

<style lang="less" scoped>
.select-cls {
  border: 1px solid #ccccccea;
  padding: 10px;
  box-sizing: border-box;
  overflow-y: auto;
}
.button-cls {
  display: flex;
  align-items: center;
}
.title {
  font-weight: bolder;
}
</style>